<template>
  <a-modal
    :maskClosable="false"
    :title="title"
    :width="1350"
    :bodyStyle="{
      padding: '0 24px'
    }"
    :visible="visible"
    @cancel="handleCancel"
    cancelText="关闭">
    <a-card
      :bordered="false"
      :bodyStyle="{
        padding: '10px 24px'
      }">
          <!-- 查询区域 -->
          <div class="table-page-search-wrapper">
            <a-form layout="inline" @keyup.enter.native="searchByquerys">
              <a-row :gutter="24">
                <a-col :xl="6" :lg="7" :md="8" :sm="24">
                  <a-form-item label="单据编号">
                    <a-input placeholder="请输入单据编号" v-model="queryParams.billNo"></a-input>
                  </a-form-item>
                </a-col>
                <a-col :xl="6" :lg="7" :md="8" :sm="24">
                    <a-form-item label="申请公司">
                      <select-Company-input placeholder="请选择申请公司"  v-model="queryParams.companyId" />
                    </a-form-item>
                  </a-col>
                  <a-col :xl="6" :lg="7" :md="8" :sm="24">
                    <a-form-item label="使用日期">
                      <j-date placeholder="请选择使用日期" v-model="queryParams.useDate" style="width: 100%"></j-date>
                    </a-form-item>
                  </a-col>
                <template v-if="toggleSearchStatuss">
                  <a-col :xl="6" :lg="7" :md="8" :sm="24">
                    <a-form-item label="借款方式">
                      <j-dict-select-tag placeholder="请选择借款方式" style="radio" v-model="queryParams.borrowMode" dictCode="borrow_money"/>
                    </a-form-item>
                  </a-col>
                  <a-col :xl="6" :lg="7" :md="8" :sm="24">
                    <a-form-item label="归还日期">
                      <j-date placeholder="请选择归还日期" v-model="queryParams.returnDate" style="width: 100%"></j-date>
                    </a-form-item>
                  </a-col>
                </template>
                <a-col :xl="6" :lg="7" :md="8" :sm="24">
                  <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
                    <a-button type="primary" @click="searchByquerys" icon="search">查询</a-button>
                    <a-button @click="searchResets(1)" icon="redo" style="margin-left: 8px">重置</a-button>
                    <a @click="handleToggleSearchs" style="margin-left: 8px">
                      {{ toggleSearchStatuss ? '收起' : '展开' }}
                      <a-icon :type="toggleSearchStatuss ? 'up' : 'down'"/>
                    </a>
                  </span>
                </a-col>
              </a-row>
            </a-form>
          </div>
          <!-- 查询区域-END -->

          <!-- table区域-begin -->
          <div>
            <a-table
              ref="tables"
              rowKey="id"
              bordered
              :scroll="{x:scrollX}"
              :columns="dragResizeColumns"
              :components="draggableComponent"
              :dataSource="dataSources"
              :pagination="ipaginations"
              :loading="loadings"
              @change="handleTableChanges"
              class="j-table-force-nowrap"
              wrapClassName="ant-modal-cust-warp">
              <span slot="action" slot-scope="text, record">
                <a @click="onDetails(record)">详情</a>
              </span>
              <a slot="projectId" slot-scope="text, record" @click="onDetail(record.projectId)">{{ text }}</a>
              <span slot="money" slot-scope="text, record">
                {{ record.amount }} /
                <a @click="getRepaymentAmount(record.id)">{{ record.repaymentAmount }}</a>
                /
                <a @click="getPaymentAmount(record.id)">{{ record.paymentAmount }}</a>
                / {{ ((record.amount).toFixed(2)-(record.repaymentAmount).toFixed(2)-(record.paymentAmount).toFixed(2)).toFixed(2) }}
              </span>
            </a-table>
            <erp-finance-repayment-slip-penetrate ref="repaymentSlip" />
            <ErpFinanceAllTravelReimbursementPenetrate ref="reimbursementPenetrate" />

            <!-- 项目详情开始 -->
            <erp-project-report-modal  ref="projectForm"></erp-project-report-modal>
          </div>

          <!-- 详情开始 -->
          <a-modal
            :maskClosable="false"
            title="借款单单据详情"
            :width="1350"
            :bodyStyle="{
              padding: '0 24px'
            }"
            :visible="visibleDetails"
            @cancel="handleCancelDetails"
            cancelText="关闭">
            <ErpFinanceLoanBillForm ref="realForms" :disabled="true" normal></ErpFinanceLoanBillForm>
            <template slot="footer">
              <a-button @click.stop="handleCancelDetails">关闭</a-button>
            </template>
          </a-modal>
          <!-- 详情结束 -->
    </a-card>
    <template slot="footer">
      <a-button @click.stop="()=>{visible=false}">关闭</a-button>
    </template>
  </a-modal>
  
</template>

<script>

  import { filterObj } from '@/utils/util';
  import { getAction } from '@/api/manage'
  import moment from 'moment'
  import SelectCompanyInput from '@/views/scy/components/SelectCompanyInput'
  import SelectCustomerInput from '@/views/scy/components/SelectCustomerInput'
  import SelectProjectInput from '@/views/scy/components/SelectProjectInput'
  import ErpFinanceRepaymentSlipPenetrate from '@/views/scy/penetrate/ErpFinanceRepaymentSlipPenetrate'
  import ErpFinanceAllTravelReimbursementPenetrate from '@/views/scy/penetrate/ErpFinanceAllTravelReimbursementPenetrate'
  import ErpProjectReportModal from '@/views/erp/report/project/modules/ErpProjectReportModal'
  import { DragResizable } from '@/mixins/DragResizable'

  export default {
    name: 'ErpFinanceTravelReimbursementPenetrate',
    components: {
      SelectCompanyInput,
      SelectCustomerInput,
      SelectProjectInput,
      ErpFinanceRepaymentSlipPenetrate,
      ErpFinanceAllTravelReimbursementPenetrate,
      ErpProjectReportModal,
      ErpFinanceLoanBillForm: ()=> import('@/views/erp/finance/borrow/modules/ErpFinanceLoanBillForm')
    },
    mixins: [DragResizable],
    props: [],
    data() {
      return {
        id:"",
        visibleDetail: false,
        activeKey: '1',
        title: '借款明细',
        queryParam: {},
        toggleSearchStatus: false,
        url: {
          queryPaymentBillById: '/api/erp/finance/payment/erpFinancePaymentSlip/queryById',
          queryReimbursementBillById: '/api/erp/finance/reimbursement/erpFinanceReimbursementBill/queryById',
          queryLoanById: '/api/erp/finance/borrow/erpFinanceLoanBill/queryById',
          queryProjectProgressBillById: '/api/erp/finance/projectProgress/erpFinanceProjectProgressPaymentApplicationBill/queryById',
          paymentUrlList: '/api/erp/finance/payment/erpFinancePaymentSlip/allList',
          projectProgressUrlList: '/api/erp/finance/projectProgress/erpFinanceProjectProgressPaymentApplicationBill/allList',
          travelUrlList: '/api/erp/finance/travel/erpFinanceTravelReimbursementBill/checkList',
          LoanBillUrlList: '/api/erp/finance/borrow/erpFinanceLoanBill/allList'
        },
        dataSource: [],
        loading: false,
        ipagination: {
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '30', '50', '100', '200'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        isorter: {
          column: 'createTime',
          order: 'desc'
        },
        scrollTrigger: { x: 'true' },
        visible: false,
        dictOptions: {},
        createTime: [],
        contractId: null,
        visibleDetails: false,
        queryParams: {},
        loadings: false,
        toggleSearchStatuss: false,
        dragResizeColumns: [
          {
            title: '序号',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: 'center',
            customRender: function (t, r, index) {
              return parseInt(index) + 1;
            }
          },
          {
            title:'单据编号',
            align:"center",
            dataIndex: 'billNo',
            scopedSlots: { customRender: 'billNo' },
            width:200,
            ellipsis: true,
          },
          {
            title:'申请公司',
            align:"center",
            dataIndex: 'companyId_dictText',
            width:232,
            ellipsis: true,
          },
          {
            title:'借款所属团队',
            align:"center",
            dataIndex: 'teamId_dictText',
            width:232,
            ellipsis: true,
          },
          {
            title:'关联项目',
            align:"center",
            dataIndex: 'projectId_dictText',
            scopedSlots: { customRender: 'projectId' },
            width:140,
            ellipsis: true,
          },
          {
            title:'借款用途',
            align:"center",
            dataIndex: 'purpose_dictText',
            width:140,
            ellipsis: true,
          },
          {
            title:'借款金额（元）/ 还款金额（元）/ 报销冲账（元）/ 未还金额（元）',
            align:"center",
            dataIndex: 'money',
            scopedSlots: { customRender: 'money' },
            width:460,
            ellipsis: true,
          },
          {
            title:'使用日期',
            align:"center",
            dataIndex: 'useDate',
            width:140,
            ellipsis: true,
            customRender:function (text) {
              return !text?"":(text.length>10?text.substr(0,10):text)
            }
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: 'center',
            fixed: 'right',
            width: 100,
            scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'action' }
          }
        ],
        dataSources: [],
        ipaginations: {
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '30', '50', '100', '200'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        isorters: {
          column: 'createTime',
          order: 'desc'
        },
        createTimeRange: [],
        type: ''
      }
    },
    created() {
      // this.loadData();
      // 该方法触发屏幕自适应
      this.resetScreenSize();
      this.refresh();
      // 加载数据字典信息
      this.initDictConfig();
      this.dragResizeColumnswidth = this.dragResizeColumns.map(val => {
        return val.width
      })
    },
    computed: {
    },
    methods: {
       // 打开还款金额明细弹窗
      getRepaymentAmount(billId) {
        //先清空数据
        this.$refs.repaymentSlip.dataSource = []
        this.$refs.repaymentSlip.ipagination.total = 0
        //查询数据
        this.$refs.repaymentSlip.loading = true
        this.$refs.repaymentSlip.loanBillId = billId
        this.$refs.repaymentSlip.searchReset()
        //打开弹窗
        this.$refs.repaymentSlip.visible = true
      },
      // 打开报销冲账明细弹窗
      getPaymentAmount(billId){
        //查询数据
        this.$refs.reimbursementPenetrate.loanBillId = billId
        this.$refs.reimbursementPenetrate.activeKey = '1'
        this.$refs.reimbursementPenetrate.callback(1)
        //打开弹窗
        this.$refs.reimbursementPenetrate.visible = true
      },
      onDetail(id) {
        const that = this
        this.$nextTick(() => {
          getAction(this.url.queryByProjectId, { id: id }).then((res) => {
            if (res.success) {
              const model = res.result
              that.$refs.projectForm.getDetail(model);
              that.$refs.projectForm.title = '项目一览表';
            }
          })
        })
      },
      initDictConfig() {
      },
      
      // 触发屏幕自适应
      resetScreenSize() {
        let screenWidth = document.body.clientWidth;
        if (screenWidth < 500) {
          this.scrollTrigger = { x: 800 };
        } else {
          this.scrollTrigger = {};
        }
      },
      handleCancel() {
        this.visible = false;
      },
      // 借款单
      onDetails(record) {
        this.visible = false
        this.visibleDetails = true
        // 查询费用报销单信息
        getAction(this.url.queryLoanById, { id: record.id }).then((res) => {
        if (res.success) {
            let data = res.result;
            this.$nextTick(() => {
              this.$refs.realForms.edit(data);
            });
          }
        })
      },
      handleCancelDetails() {
        this.visible = true
        this.visibleDetails = false
      },
      handleToggleSearchs() {
        this.toggleSearchStatuss = !this.toggleSearchStatuss;
      },
      handleTableChanges(paginations, filters, sorter) {
        // TODO 筛选
        if (Object.keys(sorter).length > 0) {
          this.isorters.column = sorter.field;
          this.isorters.order = sorter.order == 'ascend' ? 'asc' : 'desc'
        }
        this.ipaginations = paginations;
        this.loadDatas();
      },
      loadDatas(arg) {
        // 加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.ipaginations.current = 1;
        }
        var params = this.getQueryParamss();// 查询条件
        if (!this.id) {
          this.dataSources = []
          this.ipaginations.total = 0
          return
        } else {
          params.id_MultiString = this.id;
        }
        params.bpmStatus = '3';
        getAction(this.url.LoanBillUrlList, params).then((res) => {
          if (res.success) {
            let data = res.result
            if(data.records != undefined){
              data = data.records
            }
            this.dataSources = data
            this.ipaginations.total = res.result.total;
            // 判断是否当前页没有数据且不为第一页
            if (this.dataSources.length == 0 && this.ipaginations.current != 1) {
              this.ipaginations.current = this.ipaginations.current - 1
              this.loadDatas(this.ipaginations.current - 1);
            } else {
              this.loadings = false
            }
          }
        })
      },
      getQueryParamss() {
        let param = Object.assign({}, this.queryParams, this.isorters);
        param.field = this.getQueryFields();
        param.pageNo = this.ipaginations.current;
        param.pageSize = this.ipaginations.pageSize;
        return filterObj(param);
      },
      getQueryFields() {
        let str = 'id,';
        for (let a = 0; a < this.dragResizeColumns.length; a++) {
          str += ',' + this.dragResizeColumns[a].dataIndex;
        }
        return str;
      },
      searchResets() {
        let that = this;
        Object.keys(that.queryParams).forEach(function (key) {
          that.queryParams[key] = null;
        });
        that.loadDatas(1);
      },
      searchByquerys() {
        this.loadDatas(1);
      },
      //* ********************************************** */
      //* ********************************************* */
      refresh() {
        this.loading = true
      }
    }
  }
</script>
<style scoped>
  .ant-card-body .table-operator {
    margin-bottom: 18px;
  }

  .ant-table-tbody .ant-table-row td {
    padding-top: 15px;
    padding-bottom: 15px;
  }

  .anty-row-operator button {
    margin: 0 5px
  }

  .ant-btn-danger {
    background-color: #ffffff
  }

  .ant-modal-cust-warp {
    height: 100%
  }

  .ant-modal-cust-warp .ant-modal-body {
    height: calc(100% - 110px) !important;
    overflow-y: auto
  }

  .ant-modal-cust-warp .ant-modal-content {
    height: 90% !important;
    overflow-y: hidden
  }

  .anty-img-wrap {
    height: 25px;
    position: relative;
  }

  .anty-img-wrap > img {
    max-height: 100%;
  }

</style>
